package com.wangsd.web.common.controller;


import com.wangsd.web.MyController;
import com.wangsd.web.face.entity.Device;
import com.wangsd.web.face.entity.ServiceBusiness;
import com.wangsd.web.sys.entity.SysUser;
import com.wangsd.web.sys.service.SysUserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/common/open")
@Api(value = "open", tags = "后端通用开放controller")
@Slf4j
public class CommonController extends MyController {
    @Value("${service.url}")
    private String notifyUrl;
    @Value("${service.authApiUrl}")
    private String authApiUrl;
    @Value("${tyt.official.appid}")
    private String tytAppId;
    @Value("${tyt.official.account}")
    private String tytAccount;

    @Autowired
    SysUserService sysUserService;


    @RequestMapping(value = "/storeUserLinkOpenId", method = RequestMethod.GET)
    @ResponseBody
    public void storeUserLinkOpenId(Long storeUserId) {
        String from = notifyUrl + "/common/open/userLinkCallbak?userId=" + storeUserId;
        try {
            String url = authApiUrl + "/api/open/authorize?appid=" + tytAppId + "&from=" + URLEncoder.encode(from, "UTF-8");
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * （第三方平台）代公众号网页授权回调
     *
     * @param openid
     * @param userId 门店店员id
     * @param model
     * @return
     */
    @RequestMapping("/userLinkCallbak")
    public String authorizeCallbak(String openid, Long userId, Model model) {
        log.debug("TYT 店员关联 回调授权");

        SysUser user = sysUserService.getById(userId);
        //获取设备信息
        if (user == null) {
            model.addAttribute("msg", "店员信息异常");
            return "error";
        }
        //修改店员微信号
        user.setOpenId(openid);
        sysUserService.updateById(user);

        //配置关注公众号相关信息
        String qrUrl = "https://open.weixin.qq.com/qr/code?username=" +tytAccount;
        model.addAttribute("qrUrl", qrUrl);
        return "linkPage";
    }
}
